<?php

namespace App\Console\Commands\Cashbook;

use App\Models\Cashbook\CashbookCycleModel;
use App\Models\Cashbook\CashbookModel;
use App\Service\Cashbook\CashbookService;
use Illuminate\Console\Command;

class CycleSync extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'cashbook:cycle_sync';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '记账本周期自动同步';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $date = date('Y-m-d');
        $time = time();
        CashbookCycleModel::query()
            ->where('status', CashbookCycleModel::STATUS_DEAL_ING)
            ->where('nextTime', strtotime($date))
            ->chunk(
                100, function ($cashbookCycleModel) use ($date, $time) {
                $batchData = [];
                foreach ($cashbookCycleModel as $v) {
                    $batchData[] =
                        [
                            'shopId'     => $v->shopId,
                            'userId'     => $v->userId,
                            'recordTime' => strtotime($date),
                            'type'       => $v->type,
                            'category'   => $v->category,
                            'source'     => CashbookModel::SOURCE_PERIOD_SYNC_ADD,
                            'amount'     => $v->amount,
                            'createdAt'  => $time,
                            'cycleId'    => $v->id,
                            'remark'     => $v->remark,
                        ];
                    $updateData  = [];
                    if ($v->endTime == $v->nextTime) {//结束时间判断
                        $updateData['status'] = CashbookCycleModel::STATUS_SUCCESS;
                    } else {//继续下一个周期计算
                        $nextData = CashbookService::getNextData($date, date('Y-m-d', $v->endTime), $v->cycleType);                 //下次开始时间
                        if ($nextData) {
                            $updateData['nextTime'] = strtotime($nextData);
                        } else {
                            $updateData['status'] = CashbookCycleModel::STATUS_SUCCESS;
                        }
                    }
                    if ($updateData) {
                        CashbookCycleModel::query()->where('id', $v->id)->update($updateData);
                    }
                }
                if ($batchData) {
                    CashbookModel::batchInsertData($batchData);
                }
            }
            );
    }

}
